package com.ethanzzh.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

//工具类
public class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        sendAddr(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        sendAddr(req, resp);
    }


    public void sendAddr(HttpServletRequest req, HttpServletResponse resp) {
        String path = null;
        String md = req.getParameter("method");
        if (md != null) {
            //查看当前模块中是否有对应的方法，方法的名称和md中的内容一致，方法的参数HttpServletRequest，HttpServletResponse
            //获取到当前模块的字节码
            Class clazz = this.getClass();
            try {
                Method method = clazz.getMethod(md, HttpServletRequest.class, HttpServletResponse.class);
                if (method != null) {
                    //找到了对应的方法，执行当前方法
                    path = (String) method.invoke(this, req, resp);
                }
                if (null != path) {
                    req.getRequestDispatcher(path).forward(req, resp);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            try {
                execute(req, resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().print("您需要提交method 键值对数据");
        return null;
    }

}
